<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;

class Cpm extends Model
{
	protected $fillable = [
		'cpm_date',
		'cpm_hour',
		'cpm_interval',
		'ad_position_id',
		'ad_provider_id',
		'ctr_val',
		'cpm_val',
		'planid',
	];

	public static function getTrailCpm($adPositionId, $cpmDate, $cpmHour)
	{
		$redis = Redis::connection('default');
		$providerPositionHourlyShowKey = \App\Model\CpcConfig::CPC_PROVIDER_POSTION_SHOW_HOURLY . "{$cpmDate}.{$cpmHour}";
		// $hashKey = "{$adProviderId}:{$adPositionId}";
		$trailFinishTime = $redis->hGet($providerPositionHourlyShowKey, "condition_reached_time:{$adPositionId}");
		if (empty($trailFinishTime)) {
			return false;
		}
		$hourBeginTs = strtotime("{$cpmDate}.{$cpmHour}0000");

		$trailFinishInterval = intval(($trailFinishTime - $hourBeginTs) / 300);

		$data = self::where('ad_position_id', $adPositionId)
					 ->where('ctr_val', '!=', '-1')
					 ->where('cpm_date', $cpmDate)
					 ->where('cpm_hour', $cpmHour)
					 ->where('cpm_interval', '<=', $trailFinishInterval)
					 ->select(\DB::raw('sum(cpm_val) as trail_cpm_val'), 'ad_position_id', 'ad_provider_id')
					 ->groupBy(['ad_position_id', 'ad_provider_id'])
					 ->get();
		return $data;
	}
}